<template>
  <div class="grammar-question-container" v-loading="loadingSubmit">
    <Header :isGoBack="false">
      <template v-slot:left>
        <span class="weight-title">
          {{ checkedBookData.edition_name }}-{{ checkedBookData.grade_name }}
          <span class="el-icon-arrow-right"></span>
          闯关练习({{ checkedVideoTypeName }})
        </span>
      </template>
      <template v-slot:right>
        <div class="test-btn" v-if="paperData.isAnswer">
          <span class="btn-bg ml20">
            <el-button @click="studyContinue" class="button button-bg-second">继续</el-button>
          </span>
          <span class="btn-bg ml20">
            <el-button class="button button-bg-second" @click="goTestList">测试记录</el-button>
          </span>
          <span class="btn-bg ml20">
            <el-button class="button button-border-second" @click="goGrammarCenter">
              退出
            </el-button>
          </span>
        </div>
        <div class="test-btn" v-else>
          <span v-if="testData.test_id">时间: {{ testTime | filterTime }}</span>
          <span class="btn-bg ml20" v-if="testData.test_id">
            <el-button class="button button-bg-second" @click="submitPaper">交卷</el-button>
          </span>
          <span class="btn-bg ml20">
            <el-button class="button button-border-second" @click="goStudyCenter">
              退出
            </el-button>
          </span>
        </div>
      </template>
    </Header>
    <el-row class="grammar-question">
      <el-col class="grammar-item grammar-item-video" :style="`width: ${isShowVideo ? '38%' : '0px'}`">
        <div class="grammer-left">
          <!-- <div v-if="!isPlayingVideo" class="video-list-container scrollbar">
          </div> -->
          <div class="playing-video">
            <div class="video-play-box" v-if="!isDestoryVideo && checkedVideoData.id">
              <VideoPlay ref="videoPlay" :showId="'-1-' + checkedVideoData.id" :vid="checkedVideoData.url"
                @onPlayOver="onPlayOver" @onVideoPlay="onVideoPlay" @onVideoPause="onVideoPause"
                @onVideoDestory="onVideoDestory"></VideoPlay>
              <!-- <video
                src="http://dpv.videocc.net/23d31bf205/3/23d31bf205a8b611145dab68635f4f23_2.mp4?pid=1613721120356X1016661"
                ref="videotest"
                controls
              ></video> -->
            </div>
            <div class="video-list-container scrollbar">
              <div class="video-container">
                <div class="video-list-item" v-for="videoData in videoList" :key="videoData.id"
                  @click="playVideoData(videoData)">
                  <div class="video-play-box">
                    <VideoPlay :showId="checkedVideoType + '-' + videoData.id" :vid="videoData.url" :isPlay="false"
                      :number="videoData.number" @clickMasking="playVideoData(videoData)" :isShowPause="false">
                    </VideoPlay>
                  </div>
                  <p class="video-title" :class="checkedVideoData.id == videoData.id
                      ? 'checked-video-title'
                      : ''
                    ">
                    {{ videoData.title }}
                  </p>
                </div>
              </div>
            </div>
            <!-- <div class="back-btn">
              <el-button
                class="button button-bg-primary"
                @click="backVideoList"
              >
                更多视频
              </el-button>
            </div> -->
          </div>
        </div>
        <!-- open-video -->
        <div class="left-hidden-btn click" :class="isShowVideo ? '' : ''" @click="expandingAndCollapsing">
          <img src="@/assets/img/btn-hiddn.png" alt="" />
        </div>
      </el-col>
      <el-col class="grammar-item grammar-item-question reading-question" :style="`width: ${isShowVideo ? '62%' : '100%'};
              margin-left:${isShowVideo ? '0' : '-14'}px;`">
        <div class="question-list-container reading-question-list scrollbar">
          <QuestionList :paperData="paperData"> </QuestionList>
          <!-- <Question
            :questionType="paperData.type"
            v-for="(question, index) in paperData.questionList"
            :key="question.questionId"
            :question="question"
            :isAnswer="paperData.isAnswer"
            :totalIndex="paperData.questionList.length"
            :nowIndex="index + 1"
            :parentId="paperData.id"
          ></Question> -->
        </div>
      </el-col>
    </el-row>
    <PlayVoiceAudio ref="playVoiceAudio"></PlayVoiceAudio>
    <el-dialog :visible.sync="dialogVisibleScore" class="score-report" :close-on-click-modal="false">
      <div class="score-report-container">
        <h4 class="score-report-title">
          <img src="../../../assets/img/score-report-title.png" alt="" />
        </h4>
        <div class="score-report-contain">
          <p class="score-report-name">
            <strong>{{ homePageData.nickname }}</strong>同学：
          </p>
          <p class="score-report-score">
            于<strong>{{ $moment().format("YYYY年MM月DD日") }}</strong>
            在<strong>{{ checkedVideoTypeName }}</strong>语法训练中获得 <strong>{{ testData.score }}</strong>分，达到了<strong>{{
              levelObj[scoreAudioType] }}</strong>等级，
            <span v-if="testData.max_score">历史最高分<strong>{{ testData.max_score }}</strong>分，</span>获得了<strong>{{
              testData.add_integral }}</strong>学币，答题用时 <strong> {{ testTime | filterTime }} </strong>。
          </p>
          <p class="score-report-text">继续加油！再接再厉！</p>
          <div class="score-report-contain-inscribe">
            <p>智慧1+1英语测评中心</p>
            <p>{{ $moment().format("YYYY年MM月DD日") }}</p>
          </div>
          <div class="score-report-contain-level">
            <img v-if="scoreAudioType == 1" src="../../../assets/img/icon-grade1-s.png" alt="" />
            <img v-if="scoreAudioType == 2" src="../../../assets/img/icon-grade2-s.png" alt="" />
            <img v-if="scoreAudioType == 3" src="../../../assets/img/icon-grade3.png" alt="" />
            <img v-if="scoreAudioType == 4" src="../../../assets/img/icon-grade4.png" alt="" />
            <img v-if="scoreAudioType == 5" src="../../../assets/img/icon-grade5.png" alt="" />
            <img v-if="scoreAudioType == 6" src="../../../assets/img/icon-grade6.png" alt="" />
            <img v-if="scoreAudioType == 7" src="../../../assets/img/icon-grade7.png" alt="" />
          </div>
        </div>
        <div class="score-report-bottom"></div>
      </div>
      <div class="close-btn click" @click="dialogVisibleScore = false">
        <i class="el-icon-close"></i>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Header from "@/components/Header";
import VideoPlay from "@/components/VideoPlay";
import PlayVoiceAudio from "../../../components/PlayVoiceAudio";
// import Question from "@/views/read/components/Question";
import QuestionList from "../components/grammarQuestionList";
import { getGrammarPaper } from "../../../api/index";
import {
  addVideoWatchNum,
  addVideoWatchTime,
  getGrammarVideo,
  startReadPaper,
  verifyGrammarPaper,
  getHomeData,
} from "@/api/index";
export default {
  data() {
    return {
      checkedBookData: {},
      checkedTypeId: null,
      checkedVideoType: null,
      checkedVideoTypeName: "",
      videoListData: [],
      videoList: [],
      isShowVideo: true,
      isPlayingVideo: false,
      checkedVideoData: {},
      paperData: {},
      isDestoryVideo: false,
      testData: {},
      testTimeTimer: null,
      testTime: 0,
      scoreAudioType: null,
      dialogVisibleScore: false,
      homePageData: {},
      levelObj: {
        1: "黑铁",
        2: "青铜",
        3: "白银",
        4: "黄金",
        5: "钻石",
        6: "大师",
        7: "王者",
      },
      loadingSubmit: false,
    };
  },
  methods: {
    goStudyCenter() {
      this.$confirm(`测试还未提交，是否退出`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        closeOnPressEscape: false,
      })
        .then(() => {
          this.goGrammarCenter();
        })
        .catch(() => {
          return false;
        });
    },
    getHomeData() {
      getHomeData().then((res) => {
        if (res.code == 200 && res.data) {
          this.homePageData = res.data;
        }
      });
    },
    getVideoList() {
      let data1 = [],
        data2 = [];
      data1 = this.videoListData.filter((item) => {
        return item.id == this.checkedTypeId;
      });
      if (data1.length > 0) {
        data2 = data1[0].english_grammar_vos.filter((item) => {
          return item.id == this.checkedVideoType;
        });
      }
      if (data2.length > 0) {
        this.videoList = data2[0].english_grammar_video_vos;
        if (!this.checkedVideoData || !this.checkedVideoData.id) {
          this.playVideoData(this.videoList[0]);
        }
      }
    },
    onPlayOver() {
      console.log("结束", this.checkedVideoData);
      let data = {
        book_id: this.checkedBookData.book_id,
        video_id: this.checkedVideoData.id,
        subject_id: this.checkedBookData.subject_id,
      };
      addVideoWatchNum(data).then((res) => {
        if (res.code == 200) {
          this.getGrammarVideo();
        }
      });
    },
    onVideoPlay() {
      console.log("播放", this.checkedVideoData);
    },
    onVideoPause() {
      console.log("暂停", this.checkedVideoData);
    },
    onVideoDestory(useTime) {
      console.log("销毁", this.checkedVideoData, useTime);
      if (useTime && useTime > 10) {
        this.addVideoWatchTime(useTime);
        //  console.log("有效时长：", useTime);
      }
    },
    addVideoWatchTime(valid_time) {
      let data = {
        book_id: this.checkedBookData.book_id,
        subject_id: this.checkedBookData.subject_id,
        valid_time: valid_time,
        video_id: this.checkedVideoData.id,
      };
      addVideoWatchTime(data);
    },
    playVideoData(videoData) {
      if (videoData) {
        this.checkedVideoData = videoData;
      }
      this.$nextTick(() => {
        this.$refs.videoPlay.initVideo();
      });
    },
    backVideoList() {
      //  this.$refs.videoPlay.initVideo();
      this.isPlayingVideo = false;
    },
    expandingAndCollapsing() {
      if (this.isShowVideo) {
        this.collapsingVideoList();
      } else {
        this.expandingVideoList();
      }
    },
    expandingVideoList() {
      //展开视频
      this.isShowVideo = true;
      if (this.$refs.videoPlay && this.$refs.videoPlay.isInitialized) {
        this.$refs.videoPlay.resumeVideo();
      }
      if (this.$refs.videoPlay && !this.$refs.videoPlay.isInitialized) {
        let timer = setTimeout(() => {
          this.$refs.videoPlay.initVideo();
          clearTimeout(timer);
        }, 500);
      }
    },
    collapsingVideoList() {
      //收起视频
      this.isShowVideo = false;
      if (this.$refs.videoPlay && this.$refs.videoPlay.isInitialized) {
        this.$refs.videoPlay.pauseVideo();
      }
      if (this.$refs.videoPlay && !this.$refs.videoPlay.isInitialized) {
        this.$refs.videoPlay.destroyedVideo();
      }
    },
    getGrammarVideo() {
      let params = {
        subjectId: this.checkedBookData.subject_id,
      };

      getGrammarVideo(params).then((res) => {
        if (res.code == 200 && res.data) {
          this.videoListData = res.data.filter((item1) => {
            let data1 = item1.english_grammar_vos.filter((item2) => {
              let data2 = item2.english_grammar_video_vos.filter((item3) => {
                return item3.id;
              });
              return data2.length > 0;
            });
            return data1.length > 0;
          });
          localStorage.setItem(
            "videoListData",
            JSON.stringify(this.videoListData)
          );
          this.getVideoList();
        }
      });
    },
    goGrammarCenter() {
      this.$router.push({
        name: "grammerVideo",
        query: {
          checkedTypeId: this.checkedTypeId,
          checkedVideoType: this.checkedVideoType,
          checkedVideoTypeName: this.checkedVideoTypeName,
        },
      });
    },

    studyContinue() {
      this.getGrammarPaper();
    },
    getGrammarPaper() {
      let data = {
        grammar_id: Number(this.checkedVideoType),
        source: 2,
        book_id: this.checkedBookData.book_id,
      };
      getGrammarPaper(data).then((res) => {
        //  <input class='question-input' autocomplete="off" id='-1' onpaste = "return false";></input>
        if (res.code == 200) {
          this.testData = res.data;
          let newQuestionList = [];
          res.data.grammar_question_answer_type_list.forEach((questionList) => {
            questionList.grammar_question_info_list.forEach((question) => {
              let newTitle = question.title;
              if (questionList.answer_type == 2) {
                let index = 1;
                let pos = newTitle.indexOf("_____");
                while (pos !== -1) {
                  newTitle = newTitle.replace(
                    /_{5}/,
                    ` <input class='question-input' autocomplete="off" id='input-${question.question_id}-${index}' onpaste = "return false";></input> `
                  );
                  index++;
                  pos = newTitle.indexOf("_____");
                }
                question.inputNum = index - 1;
              }
              // ` <input class='question-input' autocomplete="off" id='input-${question.question_id}' onpaste = "return false";></input>`
              newQuestionList.push({
                questionId: question.question_id,
                title: newTitle,
                answerType: question.answer_type,
                answerList: question.article_answer_info_list,
                studentAnswer: [],
                inputNum: question.inputNum,
              });
            });
          });
          this.paperData = {
            isAnswer: false,
            id: res.data.test_id,
            questionList: newQuestionList,
          };
          startReadPaper(this.testData.test_id).then((res2) => {
            if (res2.code == 200) {
              this.testTime = 0;
              this.timerFun();
            }
          });
        } else if (res.code == 405) {
          this.$alert("暂无试题");
        }
      });
    },
    timerFun() {
      this.testTimeTimer = setInterval(() => {
        this.testTime++;
      }, 1000);
    },
    submitPaper() {
      let number = 0;
      this.paperData.questionList.forEach((item) => {
        if (item.answerType == 2) {
          item.studentAnswer = [];
          for (let i = 1; i <= item.inputNum; i++) {
            let inputDom = document.getElementById(
              `input-${item.questionId}-${i}`
            );
            item.studentAnswer.push(inputDom.value.trim());
          }
        }
        if (
          !item.studentAnswer ||
          item.studentAnswer.length == 0 ||
          item.studentAnswer.some((item) => !item)
        ) {
          number++;
        }
      });
      this.$confirm(
        `${number > 0 ? "还有" + number + "道题未答，" : ""}
        是否检查完毕，确认提交？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }
      )
        .then(() => {
          this.postPaper();
        })
        .catch(() => {
          return false;
        });
    },
    postPaper() {
      console.log(this.paperData,"this.paperDatapost");
      let data = {
        source: 1,
        test_id: this.testData.test_id,
        use_time: this.testTime,
        book_id: this.checkedBookData.book_id,
        check_grammar_question_info_list: this.paperData.questionList.map(
          (item) => {
            return {
              question_id: item.questionId,
              answer_type: item.answerType,
              student_article_answer_info_list: item.studentAnswer.map(
                (sAnswer) => {
                  if (item.answerType == 2) {
                    return {
                      answer: sAnswer,
                    };
                  }
                  if (item.answerType == 1) {
                    return {
                      answer_id: sAnswer,
                    };
                  }
                }
              ),
            };
          }
        ),
      };
      this.loadingSubmit = true;
      verifyGrammarPaper(data)
        .then(async (res) => {
          this.loadingSubmit = false;
          clearInterval(this.testTimeTimer);
          if (res.code == 200) {
            this.paperData = {
              id: this.testData.test_id,
              isAnswer: true,
              questionList: res.data.student_grammar_question_answer_info_list.map(
                (question) => {
                  let answerList = [];
                  let answerListData = this.paperData.questionList.filter(
                    (item) => {
                      return item.questionId == question.question_id;
                    }
                  );
                  if (answerListData.length > 0) {
                    answerList = answerListData[0].answerList;
                  }
                  return {
                    questionId: question.question_id,
                    title: question.title,
                    inputNum: question.inputNum,
                    answerType: question.answer_type,
                    answerList: answerList,
                    isTrue: question.is_true,
                    parse: question.parse,
                    trueAnswer: question.article_answer_info_list.filter(
                      (answer) => {
                        return answer.is_true == 1;
                      }
                    ),
                    studentAnswer: question.student_article_answer_info_list
                      .filter((answer) => {
                        return answer.answer_id || answer.answer;
                      })
                      .map((answer) => {
                        return answer.answer_id || answer.answer;
                      }),
                    verifyAnswer: question.student_article_answer_info_list,
                  };
                }
              ),
            };
            this.testData = res.data;
            this.dialogVisibleScore = true;
            let type;
            if (this.testData.score == 100) {
              type = 7;
            } else if (this.testData.score >= 90 && this.testData.score <= 99) {
              type = 6;
            } else if (this.testData.score >= 80 && this.testData.score < 90) {
              type = 5;
            } else if (this.testData.score >= 70 && this.testData.score < 80) {
              type = 3;
            } else if (this.testData.score >= 60 && this.testData.score < 70) {
              type = 2;
            } else if (this.testData.score < 60) {
              type = 1;
            }
            this.scoreAudioType = type;
            this.$refs.playVoiceAudio.changeType(type, true);
          }
        })
        .catch(() => {
          this.loadingSubmit = false;
        });
    },
    goTestList() {
      this.$router.push({
        name: "grammarTestList",
        query: {
          checkedTypeId: this.checkedTypeId,
          checkedVideoType: this.checkedVideoType,
          checkedVideoTypeName: this.checkedVideoTypeName,
        },
      });
    },
  },
  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    this.checkedTypeId = this.$route.query.checkedTypeId;
    this.checkedVideoType = this.$route.query.checkedVideoType;
    this.checkedVideoTypeName = this.$route.query.checkedVideoTypeName;
    this.videoListData = JSON.parse(localStorage.getItem("videoListData"));
    if (!this.videoListData || !this.checkedVideoType) {
      this.$router.push({
        name: "grammarVideo",
      });
    }
    this.getVideoList();
    this.getGrammarPaper();
    this.getHomeData();
  },
  mounted() {
    // this.$refs.videotest.play();
    // this.$refs.videotest.pause();
  },
  beforeDestroy() {
    clearInterval(this.testTimeTimer);
  },
  components: {
    Header,
    VideoPlay,
    // Question,
    QuestionList,
    PlayVoiceAudio,
  },
};
</script>